package com.xingfly.security.jwt.resolvers;

import com.xingfly.model.User;
import com.xingfly.security.jwt.annotation.CurrentUser;
import com.xingfly.security.jwt.util.JwtConstants;
import com.xingfly.security.jwt.util.JwtTokenUtil;
import com.xingfly.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * 将有@CurrentUser 注解的用户类 直接 注入 当前user对象
 * Created by SuperS on 22/12/2016.
 */
@Component
public class CurrentUserResolvers implements HandlerMethodArgumentResolver {
    @Autowired
    private AccountService accountService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (methodParameter.getParameterType().isAssignableFrom(User.class) &&
                methodParameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String username = jwtTokenUtil.getUsernameFromToken(nativeWebRequest.getHeader(JwtConstants.JWT_TOKEN_HEADER_PARAM));
        if(username!=null){
            return accountService.find(username);
        }
        return new MissingServletRequestPartException(JwtConstants.JWT_TOKEN_HEADER_PARAM);
    }
}
